﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Store;
using Lucene.Net.Search;
using Lucene.Net.QueryParsers;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;

namespace LuceneWInFormDemo
{
    class Searcher
    {
        private Lucene.Net.Store.Directory index;
        public long TimeLastAction
        { get; private set; }
        public int PageSize
        { get; private set; }
        private TopDocCollector result;
        private IndexSearcher searcher;
        private string query;

        /// <summary>
        /// Constructor
        /// </summary>
        public Searcher(string indexPath)
        {
            index = FSDirectory.GetDirectory(indexPath);
        }

        //public TopDocCollector Search(string queryString)
        //{
        //    return Search(queryString, 0);
        //}

        /// <summary>
        /// Search the index
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        //public TopDocCollector Search(string queryString, int page)
        public TopDocCollector Search(string queryString)
        {
            long start = DateTime.Now.Millisecond;
            if (!query.Equals(queryString) || result == null)
            {
                query = queryString;
                Query q = new QueryParser("contents", new SimpleAnalyzer()).Parse(queryString);
                searcher = new IndexSearcher(index);
                result = new TopDocCollector(PageSize);
                searcher.Search(q, result);
            }
            long end = DateTime.Now.Millisecond;
            TimeLastAction = end - start;
            return result;
        }

        public Document Doc(int id)
        {
            return searcher.Doc(id);
        }
    }
}
